//
//  MJLoadHistoryView.m
//  Weike
//
//  Created by leirz on 14-8-21.
//  Copyright (c) 2014年 winupon. All rights reserved.
//

#import "MJLoadHistoryView.h"
#import "AppUtils.h"

@implementation MJLoadHistoryView
{
    UIView *loadingView;
    BOOL isRefreshing;
    CGFloat contentHeight;
    NSTimeInterval lastTime;
}

- (id)init
{
    self = [super init];
    if (self) {
        [self initSubviews];
    }
    return self;
}

- (void)initSubviews
{
    loadingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - 30) / 2, 5, 30, 30)];
    activityView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    [activityView startAnimating];
    [loadingView addSubview:activityView];
}

- (void)setTableView:(UITableView *)tableView
{
    // 移除之前的监听器
    [_tableView removeObserver:self forKeyPath:@"contentOffset" context:nil];
    // 监听contentOffset
    [tableView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
    // 设置scrollView
    _tableView = tableView;
    
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (isRefreshing || self.isStopRefresh) {
        return;
    }
    if (_tableView.contentOffset.y == 0) {
        return;
    }
    if ([AppUtils isScrollToTop:_tableView]) {
        if (isRefreshing) {
            return;
        }
        NSTimeInterval nowTime = [[NSDate date] timeIntervalSince1970];
        if (lastTime > 0 && nowTime - lastTime < 1) {
            return;
        }
        lastTime = nowTime;
        _tableView.tableHeaderView = loadingView;
        isRefreshing = YES;
        if (_beginRefreshingBlock != nil) {
            [AppUtils delay:^{
                _beginRefreshingBlock();
            } delayTime:0.3];
        }
    }
}

- (void)endRefreshing
{
    _tableView.tableHeaderView = nil;
    isRefreshing = NO;
    CGPoint offset = _tableView.contentOffset;
    offset.y = _tableView.contentSize.height - contentHeight + offset.y - 40;
    [_tableView setContentOffset:offset animated:NO];
    contentHeight = _tableView.contentSize.height;
}

- (void)update
{
    contentHeight = _tableView.contentSize.height;
}

- (void)setStopRefresh:(BOOL)stopRefresh
{
    _stopRefresh = stopRefresh;
    isRefreshing = NO;
    _tableView.tableHeaderView = nil;
}

- (void)free
{
    if(_tableView){
        [_tableView removeObserver:self forKeyPath:@"contentOffset" context:nil];
    }
}

@end
